﻿using System;
using System.Diagnostics;
using System.Threading;
using UtilZ.Dotnet.Ex.Base;

namespace ConAppCore.Test
{
    internal class TestProcessEx
    {
        public static void Test()
        {
            //TestExecuteCommand();
            //TestExecuteCommand2();

            //TestGetProcessIdByPort();

            TestProcessResourseUsageInfo();

        }


        private static void TestProcessResourseUsageInfo()
        {
            var pro = new ProcessEx();
            pro.AssociateProcess(Process.GetProcessById(15012));

            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(2000);
                ProcessResourseUsageInfo processResourseUsageInfo = pro.GetProcessResourseUsageInfo();
                Console.WriteLine($"CPU:{processResourseUsageInfo.CPUUsageRate}%     mem:{UnitConverter.ByteToMB(processResourseUsageInfo.MemoryUsage)}MB      th:{processResourseUsageInfo.ThreadNum}");
            }
        }

        private static void TestGetProcessIdByPort()
        {
            //var pidList1 = ProcessEx.GetProcessIdByPort(9057, true);
            //var pidList2 = ProcessEx.GetProcessIdByPort(9057, false);
            //var pidList3 = ProcessEx.GetProcessIdByPort(9057, null);

            var pidList1 = ProcessEx.GetProcessIdByPort(5401, true);
            var pidList2 = ProcessEx.GetProcessIdByPort(5401, false);
            var pidList3 = ProcessEx.GetProcessIdByPort(5401, null);

        }


        private static void TestExecuteCommand2()
        {
            //string app = "PING.EXE";
            ////int count = 4;
            ////string args = string.Format("{0} -S {1} -n {2}", serverIp, clientIp, count);
            //string args = "ping 192.168.10.11 -S 192.168.10.96 -n 3";
            ////string pingResultStr = ProcessEx.SynExcuteCmd(app, args);
            //string pingResultStr = ProcessEx.ExecuteCommand(args);
            //bool ret = NetHelper.ValidateClientIpPingServerIp("192.168.10.96", "192.168.10.11");
        }

        private static void TestExecuteCommand()
        {
            string retText = null;
            try
            {
                switch (Environment.OSVersion.Platform)
                {
                    case PlatformID.Win32NT:
                        //string app = "PING.EXE";
                        //int count = 4;
                        //string args = string.Format("{0} -S {1} -n {2}", serverIp, clientIp, count);
                        //retText = WindowsExecuteCommand("ipconfig");
                        //retText = RefreshPortUseList();
                        retText = ExecuteCommand("netstat -aon");
                        break;
                    case PlatformID.Unix:
                        retText = LinuxExecuteCommand("netstat -tunp");
                        break;
                    case PlatformID.Other:
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }


        /// <summary>
        /// 执行命令行程序并返回输出结果字符串
        /// </summary>
        /// <param name="commandLine">要执行的命令行</param>
        /// <returns>执行输出结果字符串</returns>
        private static string ExecuteCommand(string commandLine)
        {
            var process = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo()
                {
                    //FileName = appPath,
                    Arguments = string.Empty,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    WindowStyle = ProcessWindowStyle.Hidden,
                },
                //EnableRaisingEvents = true
            };

            switch (Environment.OSVersion.Platform)
            {
                case PlatformID.Win32NT:
                    process.StartInfo.FileName = @"cmd.exe";
                    break;
                case PlatformID.Unix:
                    process.StartInfo.FileName = @"/bin/bash";
                    break;
                case PlatformID.MacOSX:
                default:
                    throw new NotImplementedException($"未实现的OS平台\"{Environment.OSVersion.Platform.ToString()}\"");
            }

            //pro.Exited += (s, e) =>
            //{
            //    autoResetEvent.Set();
            //};

            try
            {
                process.Start();
                process.StandardInput.WriteLine(commandLine);
                //process.StandardInput.WriteLine("cls");
                //process.StandardInput.WriteLine("exit");
                process.StandardInput.Close();
                string resultText = process.StandardOutput.ReadToEnd();
                process.StandardOutput.Close();
                process.WaitForExit();
                process.Dispose();
                return resultText;
            }
            finally
            {
                process.Dispose();
            }
        }

        /// <summary>
        /// 执行Linux命令行程序并返回输出结果字符串
        /// </summary>
        /// <param name="commandLine">要执行的命令行</param>
        /// <returns>执行输出结果字符串</returns>
        private static string LinuxExecuteCommand(string commandLine)
        {
            var process = new System.Diagnostics.Process
            {
                StartInfo = new System.Diagnostics.ProcessStartInfo("/bin/bash", "")
                {
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    UseShellExecute = false
                }
            };

            try
            {
                //process.StartInfo.RedirectStandardInput = true;
                //process.StartInfo.RedirectStandardOutput = true;
                //process.StartInfo.UseShellExecute = false;
                process.Start();
                process.StandardInput.WriteLine(commandLine);
                //process.StandardInput.WriteLine("netstat -an |grep ESTABLISHED |wc -l");
                process.StandardInput.Close();
                string resultText = process.StandardOutput.ReadToEnd();
                process.WaitForExit();
                return resultText;
            }
            finally
            {
                process.Dispose();
            }
        }
    }
}
